package cc.eddic.practice.concurrency;


import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Objects;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;

/**
 * 文件工具类
 */
@Slf4j
public class FileUtil {
    public static Stream<String> gzipReader(final String gzipFilePath) throws IOException {
        FileInputStream fileInputStream = null;
        GZIPInputStream gzipInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;

        try {
            fileInputStream = new FileInputStream(gzipFilePath);
            gzipInputStream = new GZIPInputStream(fileInputStream);
            inputStreamReader = new InputStreamReader(gzipInputStream);
            bufferedReader = new BufferedReader(inputStreamReader);

            FileInputStream finalFin = fileInputStream;
            GZIPInputStream finalGzin = gzipInputStream;
            InputStreamReader finalIsr = inputStreamReader;
            BufferedReader finalBr = bufferedReader;
            return bufferedReader.lines()
                    .onClose(() -> closeHandler(finalBr, finalIsr, finalGzin, finalFin));
        } catch (IOException ex) {
            closeHandler(bufferedReader, inputStreamReader, gzipInputStream, fileInputStream);
            throw ex;
        }
    }

    private static void closeHandler(AutoCloseable... closeableList) {
        Arrays.stream(closeableList).filter(Objects::nonNull).forEach(c -> {
            try {
                if (log.isDebugEnabled()) log.debug("{} close", c.getClass().getName());
                c.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        });
    }
}
